//
//  LoginViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/1/16.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "LoginViewController.h"
//#import "LJImageRollingView.h"
//#import "SelectWebUrlViewController.h"
#import "RegisterViewController.h"
#import <ShareSDK/ShareSDK.h>
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
//#import <ShareSDKExtension/ShareSDKExtension.h>
#import <ShareSDKExtension/ShareSDK+Extension.h>

@interface LoginViewController ()<UITextFieldDelegate>{//LJImageRollingViewDelegate
    UIView *viewBG;
    UITextField *txtAccount;
    UITextField *txtPwd;
    
    UIButton *subBtn;
    float viewH;
    
    BOOL boolLogin;
    UIImageView *imageLogo;
//    LJImageRollingView *imageRolling;
}

@end

@implementation LoginViewController


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    //注册监听键盘事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault];
    txtAccount.text=[[Utility Share] userAccount];
    txtPwd.text=[[Utility Share] userPwd];
    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        
//      
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//            
//        });
//    });
    
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initComponents];
}


- (void)initComponents{
    float fh=300/640.0*kScreenWidth;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    if (kScreenHeight>600) {
        viewH =550.0;
    }else{
        viewH =480.0;
    }
    //    viewH =480.0 * kScreenWidth / 320.0;
    viewBG=[[UIView alloc]initWithFrame:CGRectMake(0, (kScreenHeight-viewH)/2.0, kScreenWidth, viewH)];//
    viewBG.backgroundColor=[UIColor clearColor];
    [self.view addSubview:viewBG];
    
    UIControl *closeC=[[UIControl alloc]initWithFrame:viewBG.bounds];
    [closeC addTarget:self action:@selector(closeButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [viewBG addSubview:closeC];
    
    float ftw=120.0 * kScreenWidth/320.0;
    
    UIImageView *imageAcountBG;
    UIImageView *imagePwdBG;
    imageLogo=[RHMethods imageviewWithFrame:CGRectMake((W(viewBG)-ftw)/2.0, 20, ftw, ftw) defaultimage:@"logo070116" contentMode:UIViewContentModeScaleAspectFit];
    [viewBG addSubview:imageLogo];
    
    float fy=viewH-300;
    if (viewH==480) {
        fy=viewH-310;
    }else if(kScreenHeight>570){
        CGRect  viewFramw = [imageLogo convertRect:imageLogo.frame toView:self.view ];
        float fTemp=viewFramw.origin.y+viewFramw.size.height;
//        160
        float f_jg= H(self.view)-fh-fTemp-140;
        fy=YH(imageLogo)+f_jg/2;
    }
    imageAcountBG=[RHMethods imageviewWithFrame:CGRectMake(20,fy, W(viewBG)-40, 40) defaultimage:@"dl_shouji070116" stretchW:40 stretchH:20];
    [viewBG addSubview:imageAcountBG];
   
    
    txtAccount=[RHMethods textFieldlWithFrame:CGRectMake(X(imageAcountBG)+50, Y(imageAcountBG)+5, W(imageAcountBG)-60, 30) font:Font(15) color:RGBACOLOR(50, 50, 50, 1) placeholder:@"请输入手机号" text:@""];
    txtAccount.delegate=self;
//    [txtAccount setKeyboardType:UIKeyboardTypePhonePad];
    [viewBG addSubview:txtAccount];
    
    
    imagePwdBG=[RHMethods imageviewWithFrame:CGRectMake(X(imageAcountBG), YH(imageAcountBG)+10, W(imageAcountBG), 40) defaultimage:@"dl_suo070116" stretchW:40 stretchH:20];
    [viewBG addSubview:imagePwdBG];
   
    
    txtPwd=[RHMethods textFieldlWithFrame:CGRectMake(X(imagePwdBG)+50, Y(imagePwdBG)+5, W(imagePwdBG)-60, 30) font:Font(15) color:RGBACOLOR(50, 50, 50, 1) placeholder:@"请输入密码" text:@""];
    txtPwd.delegate=self;
    [txtPwd setSecureTextEntry:YES];
    [viewBG addSubview:txtPwd];
    
    
    subBtn=[RHMethods buttonWithFrame:CGRectMake(X(imageAcountBG),viewH==480? YH(imagePwdBG)+15: YH(imagePwdBG)+25, W(imageAcountBG), 40) title:@"登录" image:@"" bgimage:@"LoginbtnBG"];
    subBtn.titleLabel.font=Font(20);
    [subBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [subBtn addTarget:self action:@selector(submintButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [viewBG addSubview:subBtn];
    
    
    //--------------------------v4.0--------------------------
    UIButton *btnPwd=[RHMethods buttonWithFrame:CGRectMake(0, YH(subBtn), 120, 40) title:@"忘记密码？" image:nil bgimage:nil];
    [btnPwd setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [btnPwd setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
    btnPwd.titleLabel.font=Font(13);
    [btnPwd setTitleColor:rgbTitleDeepGray forState:UIControlStateNormal];
    [btnPwd addTarget:self action:@selector(pwdButtonClicekd) forControlEvents:UIControlEventTouchUpInside];
    [viewBG addSubview:btnPwd];
    
    UIButton *btnRegister=[RHMethods buttonWithFrame:CGRectMake(kScreenWidth-120, YH(subBtn), 120, 40) title:@"立即注册" image:nil bgimage:nil];
    [btnRegister setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [btnRegister setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 20)];
    btnRegister.titleLabel.font=Font(13);
    [btnRegister setTitleColor:rgbpublicColor forState:UIControlStateNormal];
    [btnRegister addTarget:self action:@selector(registerButtonClicekd) forControlEvents:UIControlEventTouchUpInside];
    [viewBG addSubview:btnRegister];
    
    BOOL isInstallWx = [ShareSDK isClientInstalled:SSDKPlatformTypeWechat];
  

    NSInteger num=0;
    if (isInstallWx) {
        num++;
    }
    if ([ShareSDK isClientInstalled:SSDKPlatformTypeQQ]) {
        num++;
    }
    if (num>0) {
        [self.view addSubview:[RHMethods lineViewWithFrame:CGRectMake(10, kScreenHeight-102.5, kScreenWidth-20, 0.5)]];
        UILabel *lblT=[RHMethods labelWithFrame:CGRectMake((kScreenWidth-70)/2, kScreenHeight-112, 70, 20) font:Font(13) color:rgbTitleDeepGray text:@"第三方登录" textAlignment:NSTextAlignmentCenter];
        lblT.backgroundColor=[UIColor whiteColor];
        [self.view addSubview:lblT];

    }
    
    float fx=kScreenWidth/2-80;
    if (num==1) {
        fx=kScreenWidth/2-40;
    }
    if (isInstallWx) {
        UIButton *btnWx=[RHMethods buttonWithFrame:CGRectMake(fx, kScreenHeight-100, 80, 100) title:nil image:@"wxicon" bgimage:nil];
        [btnWx addTarget:self action:@selector(wxButtonClicekd) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btnWx];
        fx+=80;

    }
    if ([ShareSDK isClientInstalled:SSDKPlatformTypeQQ]) {
        UIButton *btnQQ=[RHMethods buttonWithFrame:CGRectMake(fx, kScreenHeight-100, 80, 100) title:nil image:@"qqiconLogin" bgimage:nil];
        [btnQQ addTarget:self action:@selector(QQButtonClicekd) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btnQQ];
//

    }
    
    
    
    //----------------------------------------------------
    
    
    
    [[Utility Share] setIsUserLogin:NO];
    
    
    boolLogin=NO;
    
//    imageRolling=[[LJImageRollingView alloc]initWithFrame:CGRectMake(0, H(self.view)-fh, kScreenWidth, fh)];
//    [self.view addSubview:imageRolling];
//    imageRolling.autoresizingMask=UIViewAutoresizingFlexibleTopMargin;
//    imageRolling.delegateDiscount=self;
////    [imageRolling reloadImageView:@[@{@"DefaultImage":[UIImage imageNamed:@"dl_gg070116"]}] selectIndex:0];
    
    [self isLoginStatus];
//    [self welcomeLoginAdvertising];
}
-(void)welcomeLoginAdvertising{
////    XKFwelcome
//    [NetEngine createGetAction_LJ:XKFV3homesad onCompletion:^(id resData, BOOL isCache) {
//        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
//            NSMutableArray *arrayA=[NSMutableArray new];
//            for (NSDictionary *dc in [[resData objectForJSONKey:@"data"] objectForJSONKey:@"list"]) {
//                NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:dc];
//                [dic setValue:[dc valueForJSONStrKey:@"2x_path"] forKey:@"url"];
//                [arrayA addObject:dic];
//            }
//            [imageRolling reloadImageView:arrayA selectIndex:0];
//        }else{
//            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
//        }
//    }];
}
-(void)isLoginStatus{
    
    [self performSelector:@selector(hiddenTransitionView) withObject:self afterDelay:0.5];
    
}
-(void)hiddenTransitionView{
    [[Utility Share] hiddenStartTransitionView];
}
-(void)hiddenTransitionView_OnlyOne{
    [[Utility Share] hiddenStartTransitionView];
    
}
#pragma mark button
-(void)submintButtonClicked{
    boolLogin=YES;
    
  
    [self closeButtonClicked];
    
//    //分享授权
//    if ([ShareSDK hasAuthorized:SSDKPlatformTypeSinaWeibo]) {
//        [ShareSDK cancelAuthorize:SSDKPlatformTypeSinaWeibo];
//    }
    
    NSString *strAc=txtAccount.text;
    NSString *strPwd=txtPwd.text;
    
    if (![strAc notEmptyOrNull])
    {
        [SVProgressHUD showImage:nil status:@"请填写账号"];
        return;
    }
    
    if (![strPwd notEmptyOrNull])
    {
        [SVProgressHUD showImage:nil status:@"密码不能为空"];
        return;
    }
    [[Utility Share] isLoginAccount:strAc pwd:strPwd code:nil aLogin:^(NSInteger NoLogin) {
        if (NoLogin==1) {
            
            
        }
        
    }];
    
    
    
    
    
    
    
}
-(void)closeButtonClicked{
    [txtAccount resignFirstResponder];
    [txtPwd resignFirstResponder];
    
}

#pragma mark text
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==txtAccount) {
        [txtPwd becomeFirstResponder];
    }else{
        [self submintButtonClicked];
    }
    return YES;
}


#pragma mark serlector
-(void)handleKeyboardDidShow:(NSNotification *)notification{
    
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame;
    [[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
    CGFloat distanceToMove = kbSize.height;
    NSLog(@"---->动态键盘高度:%f",distanceToMove);
    if (distanceToMove<20) {
        return;
    }
    float t_y=(Y(viewBG)+distanceToMove +YH(subBtn)+10)-kScreenHeight;
    
    NSLog(@"---->动态键盘高度:%f:::::<%f",distanceToMove,t_y);
    
    [UIView animateWithDuration:0.3 animations:^{
        viewBG.frame=CGRectMake(X(viewBG), Y(viewBG) - t_y, W(viewBG),H(viewBG));
        
    }];
}
- (void)handleKeyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3 animations:^{
        viewBG.frame=CGRectMake(X(viewBG), (kScreenHeight-viewH)/2.0, W(viewBG),H(viewBG));
        
        
    }];
}//


//#pragma mark LJImageRollingViewDelegate
//-(void)selectView:(LJImageRollingView *)selectView ad:(NSDictionary *)dic index:(NSInteger)index{
//    if ([[dic valueForJSONStrKey:@"links"] notEmptyOrNull]) {
//         [self pushController:[SelectWebUrlViewController class] withInfo:@"" withTitle:@"" withOther:@{@"url":[dic valueForJSONStrKey:@"links"]}];
//    }   
//}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

//是否支持屏幕旋转
-(BOOL)shouldAutorotate
{
    return NO;
}

// 支持的旋转方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    
    return UIInterfaceOrientationMaskPortrait;//UIInterfaceOrientationMaskAllButUpsideDown;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    
    return UIInterfaceOrientationPortrait;
}
#pragma mark - v4 button
-(void)registerButtonClicekd{
    [self pushController:[RegisterViewController class] withInfo:@"register" withTitle:@"立即注册" withOther:nil];
}
-(void)pwdButtonClicekd{
    [self pushController:[RegisterViewController class] withInfo:@"pwd" withTitle:@"找回密码" withOther:nil];
}
-(void)wxButtonClicekd{
    [self otherTypeLogin:SSDKPlatformTypeWechat];
//
}
-(void)QQButtonClicekd{
    [self otherTypeLogin:SSDKPlatformTypeQQ];
}
-(void)otherTypeLogin:(SSDKPlatformType)type{
    NSMutableDictionary *dicT=[NSMutableDictionary new];
    if (type==SSDKPlatformTypeQQ) {
        [dicT setValue:@"qq" forKey:@"type"];
    }else if(type==SSDKPlatformTypeWechat){
        [dicT setValue:@"weixin" forKey:@"type"];
   
    }
    
    [ShareSDK getUserInfo:type
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
     {
         if (state == SSDKResponseStateSuccess)
         {
             [dicT setValue:user.uid forKey:@"openid"];
             [dicT setValue:user.nickname forKey:@"nickname"];
             [dicT setValue:user.icon forKey:@"icon"];
             [self loginThirdPartyShareSDK:dicT];
             
             [ShareSDK cancelAuthorize:type];
         }else if (state==SSDKResponseStateFail){
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登录失败"
                                                             message:[NSString stringWithFormat:@"%@",error]
                                                            delegate:nil
                                                   cancelButtonTitle:@"OK"
                                                   otherButtonTitles:nil, nil];
             [alert show];
         }else
         {
             NSLog(@"%@",error);
         }
         
     }];
}

-(void)loginThirdPartyShareSDK:(NSDictionary *)dic{
    DLog(@"_________dic:%@",dic);
    [NetEngine createPostAction:XKFV4welcometposlogin withParams:dic onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            NSDictionary *userDict = [resData objectForJSONKey:@"data"];
            [[Utility Share] setUserId:[userDict valueForJSONStrKey:@"uid"]];
            [[Utility Share] setUserToken:[userDict valueForJSONStrKey:@"token"]];
//            [[Utility Share] setUserInfo:userDict];
            [[Utility Share] saveUserInfoToDefault];
            [[Utility Share] setUserIsADD:[[userDict valueForJSONStrKey:@"type"] isEqualToString:@"4"]];//type    int        用户类型(1
            [[Utility Share] hiddenLoginAlert:YES];
        }else if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"201"]){
            
            [self pushController:[RegisterViewController class] withInfo:@"other" withTitle:@"绑定手机" withOther:[resData objectForJSONKey:@"data"]];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
